// Basecamp+
// By James Hall

// Add jQuery - the reason I'm using jQuery, is because I prefer it, and it wouldn't be wise to rely on prototype, as 
// 37 signals may choose to update to a new version, or change the way some things work.

// This needs to initialise AFTER the basecamp stuff in order to work.
if(unsafeWindow.Event != 'undefined')
{
	unsafeWindow.Event.observe(window, 'load', function(){
	
		var GM_JQ = document.createElement('script');
		GM_JQ.src = 'chrome://basecamp_plus/content/jquery-1.2.1.js';
		GM_JQ.type = 'text/javascript';
		document.getElementsByTagName('head')[0].appendChild(GM_JQ);
	
		// Check if jQuery's loaded
		function GM_wait() 
		{
			if(typeof unsafeWindow.jQuery == 'undefined') 
			{ 
				window.setTimeout(GM_wait,100); 
			}
			else 
			{ 
				$j = unsafeWindow.jQuery.noConflict(); 
				basecampPlus(); 
			}
		}
		GM_wait();
	
		function basecampPlus() 
		{
			// Shortcut to firebug
			
			var console;
			// Thanks to Joe Hewitt for this code based on firebugx
			// Stops errors occuring if firebug is not installed
			if (!unsafeWindow.console)
			{
					var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
					"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
			
					unsafeWindow.console = {};
					for (var i = 0; i < names.length; ++i)
							unsafeWindow.console[names[i]] = function() {}
			}

			console = unsafeWindow.console;
			
			// Default features, this need to be configurable
			todosExportAsText();
			todosAddMultiple();
			
			var projectId = document.location.href.match(/.*\.com\/projects\/(.*[^\/])\//)[1];
			var baseUrl = document.location.href.match(/(.*)\.com/)[0];
			
			// Basecamp+
			$j('#floatright, h3.global').prepend('<a href="http://code.google.com/p/basecampplus/" id="bcp_header">Basecamp+</a> <span class="pipe">|</span>');
			
			function todosExportAsText()
			{
				var additionalLinks = '|&nbsp;<a href="#" class="admin" id="bcp_lists_as_text">View lists as text</a>';
				$j('#normal_list_controls').append(additionalLinks);	
				
				var textarea = '<div id="bcp_lists_text_wrapper" style="">';
				textarea += '<textarea id="bcp_lists_text" style=""></textarea>';
				textarea += '<a href="#" class="admin" id="bcp_lists_text_close">Close</a></div>';
				$j('body.todos #widgets').prepend(textarea);
				$j('#bcp_lists_text_close').click(function(){ $j('#bcp_lists_text_wrapper').slideUp(200); }); 
				
				$j('#bcp_lists_as_text').click(function(){
					//alert('ok')
					var output = '';
					$j('div.list').each(function(){
						//console.log(this);
						//console.log($j('h2 a', $j(this)).text());
						output += '\n' + $j('h2 a', $j(this)).text() + '\n\n';
						
						$j('.items_wrapper .content .content', $j(this)).each(function(){
							output += '* ' + $j(this).text() + '\n';
						});
						
					});
					
					if(output == '')
					{
						alert('There are no lists to view as text!');
					}
					else
					{
						$j('#bcp_lists_text').val(output);
						$j('#bcp_lists_text_wrapper').slideDown(200);
					}			
					
					
				});
			}
			
			function todosAddMultiple()
			{
				$j('body.todos .link_to_add_child').append(' or <a href="#" class="admin bcp_add_multiple_link">Add multiple items</a>');
				
				
				var multipleAddForm = '<form>';
				multipleAddForm += '<p>Enter to-do items (each line will be inserted as a seperate to-do item)<br/>';
				multipleAddForm += '<textarea rows="3" name="content" class="new_item_field"/>';
				multipleAddForm += '</p>';
				//multipleAddForm += '<p>Who\'s responsible?<br/>';
				//multipleAddForm += '<select><option value="">Anyone</option><option value="1889374">Me (James Hall)</option><option value="">----------</option><option value="c752663">JAMES HALL</option></select>';
				
				
				//multipleAddForm += '<span id="notify_list_2739039_new_item" style="display: none;">';
      	//multipleAddForm += '<input type="checkbox" checked="" value="1" name="notify"/> Notify by email?';
      	//multipleAddForm += '</span>';
      	//multipleAddForm += '</p>';
      	multipleAddForm += '<p class="submit"><input type="submit" value="Add these items"/> <span>or</span> ';
      	multipleAddForm += '<a href="#" class="admin bcp_add_multiple_done">I\'m done adding items</a>';
      	multipleAddForm += '</p></form>';
				
				$j('.add_item').append('<div class="bcp_add_multiple">' + multipleAddForm + '</div>');
				
				$j('.bcp_add_multiple_done').click(function(){
						console.log('done');
						var parent = $j(this).parent().parent().parent().parent();
						console.log(parent);
						$j('.bcp_add_multiple', parent).hide().removeClass('busy');
						$j('.bcp_add_multiple textarea', parent).val('');
						$j(".link_to_add_child", parent).show();				
						
						return false;
				});
				
				$j('.bcp_add_multiple_link').click(function(){
					
					var parent = $j(this).parent();
					parent.hide();
					$j('.bcp_add_multiple', parent.parent()).show();
					
					return false;
				});
				
				$j('.bcp_add_multiple form').submit(function(){
					
					//console.log($j(this).parent().parent().parent().attr('id'));
					var listId = $j(this).parent().parent().parent().attr('id').replace(/show_list_/, '');
					
					console.log(projectId);
					console.log(listId);
					
					var url = baseUrl + '/projects/' + projectId + '/todos/create_item/' + listId;
					console.log(url);
					
					$j(this).parent().addClass('busy');
					
					//$("list_2739039_new_item").addClassName("busy"); 
					
					var textareaValue = '\n' + $j('textarea', $j(this)).val();
					todoItems = textareaValue.replace(/\n\* /g, '\n').split('\n');
					var i = 0;
					//$j.each(todoItems, function(i, text){
							//console.log(this);
					saveTodoItem(0, todoItems);
					
					function saveTodoItem(i, todoItems)
					{
							new unsafeWindow.Ajax.Request
							(
								'/projects/' + projectId + '/todos/create_item/' + listId, 
								{
									asynchronous:true, 
									evalScripts:true, 
									parameters: {content: $j.trim(todoItems[i])},
									onSuccess: function(){
										i++;
										if(todoItems[i] != undefined)
										{
											saveTodoItem(i, todoItems);
										}
										else
										{
											finishMultipleAdd();
										}
									}
								}
							); 
					}
					
					function finishMultipleAdd()
					{
						$j('.bcp_add_multiple').hide().removeClass('busy');
						$j('.bcp_add_multiple textarea').val('');
						$j("#link_to_add_child_list_" + listId).show();
					}
						//console.log(this);
					//});
					return false;
					
					//return false;
				
				});
			}
			
			
			
		}
	
	});
}